package proj.unions.general;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

public class SuperTools {

	private static final String RES_ROOT_PATH = "DragonBall_";
	
	private static SuperTools mSuperTools = null; 
	private static final String PREF_KEY = "";
	public static boolean isDebug = true;
	
	private List<Activity> mActivityLists = new ArrayList<Activity>();
	private Activity mActivity = null;
	private int mWidth = -1;
	private int mHeight = -1;
	
	public static SuperTools getInstance()
	{
		if (mSuperTools == null)
			mSuperTools = new SuperTools();
		return mSuperTools;
	}
	
	public void setCurActivity(Activity tpActivity) {
		mActivity = tpActivity;
		if (!isExistActivity(tpActivity))
			mActivityLists.add(tpActivity);
	}

	private boolean isExistActivity(Activity tpActivity) {
		for (int i = 0; i < mActivityLists.size(); i++) {
			if (tpActivity == mActivityLists.get(i))
				return true;
		}
		return false;
	}

	public Activity getCurActivity() {
		return mActivity;
	}
	
	// -----------------------------------------------------------------------------------
	public void showErrorDialog(final String title, final String content)
	{
		mActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub

				SCDialog.create(mActivity, title, content, "关闭", "", new OnMyClickedListener() {
					
					@Override
					public void onPositive(JSONObject data) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onNegative(JSONObject data) {
						// TODO Auto-generated method stub
						SuperTools.getInstance().releaseGameRes();
					}
				}).show();
			}
		});
	}
	
	public String getModel()
	{
		 TelephonyManager tm = (TelephonyManager) mActivity.getSystemService(Activity.TELEPHONY_SERVICE);  
		 String model = android.os.Build.MODEL;
		 return model;
	}
	
	public String getIMEI()
	{
		 TelephonyManager tm = (TelephonyManager) mActivity.getSystemService(Activity.TELEPHONY_SERVICE);  
		 String imei = tm.getDeviceId();
		 if (imei == null)
		 {
			 imei = readLocalFile("IMEI");
			 if (imei.equals(""))
			 {
				 imei = String.valueOf(getRandom());
				 imei = imei.replace("-", "");
				 writeLocalFile("IMEI", imei);
			 }
		 }
		 String iponeNum =  tm.getLine1Number();
		 String SoftwareVersion = tm.getDeviceSoftwareVersion();
		 return imei;
	}
	
	//获取手机网络类型
	public int getPhoneNetworkType()
	{
        ConnectivityManager connectionManager = (ConnectivityManager)      
        		mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);    
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        //获取网络类型(一般为移动或Wi-Fi)
        int type = networkInfo.getType();
        return type;
	}
	
	//判断网络是否已经连接
	public boolean getPhoneIsConnected()
	{
		ConnectivityManager connectionManager = (ConnectivityManager)      
	        		mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);    
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        //获取网络是否连接
        boolean flag = networkInfo.isConnected();
        return flag;
	}
	
	//设置显隐软键盘
	public void setkeyboardVisible(View v, boolean flag)
	{
		//1.得到InputMethodManager对象
		InputMethodManager imm = (InputMethodManager)mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
		//获取状态信息
		boolean isOpen = imm.isActive();//isOpen若返回true，则表示输入法打开
		if(flag)
		{
			imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
			return;
		}
		//2.调用toggleSoftInput方法，实现切换显示软键盘的功能。
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}
	
	public boolean isThird()
	{
		String unionId = PropertiesData.getInstance().getString(ProperTiesCondefine.UNION_ID);
		if(unionId.equals("-99"))
			return false;
		return true;
	}
	
	public String getVersionCode()
	{
		try {
			PackageInfo pi = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0);
			return String.valueOf(pi.versionCode);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "10000";
		}
	}
	
	public String getVersionName()
	{
		try {
			PackageInfo pi = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0);
			return String.valueOf(pi.versionName);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "10000";
		}
	}
	
	//返回apk资源路径
	public String getAPKPath()
	{	
		String packageName = RES_ROOT_PATH + mActivity.getPackageName();
		String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + packageName + "/";
		return apkPath;
	}
	
	//apk下载地址
	public String getInstallAPKPath()
	{
		String path = getAPKPath() + "InstallAPK/";
		return path;
	}
	
	//lib下载地址
	public String getDownloadLibPath()
	{
		String path = getAPKPath() + "lib/";
		return path;
	}
	
	//返回系统路径
	public String getSystemPath()
	{
		String path = mActivity.getDir("LIBRARY_DIR", Activity.MODE_PRIVATE).getPath() + "/";
		return path;
	}
	
	//res下载地址
	public String getDownloadResPath()
	{
		String path = getAPKPath() + "data/";
		return path;
	}	
		
	//判断文件是否为空
	public boolean isExistFile(String fileName)
	{
		File f = new File(fileName);
		return f.exists();
	}

	//随机数
	public long getRandom()
	{
		Random rdm = new Random(System.currentTimeMillis());
		long num = rdm.nextLong();
		return num;
	}
	
	//判断string是字母还是数字还是中文
	public static int getStringType(String content)
	{
		Pattern p = Pattern.compile("[0-9]*"); 
	    Matcher m = p.matcher(content); 
	    if( m.matches() )
	    	return 0;	//数字
	    
	    p = Pattern.compile("[a-zA-Z]");
	    m = p.matcher(content);
	    if( m.matches() )
	    	return 1;	//字母

	    p = Pattern.compile("[\u4e00-\u9fa5]");
	    m = p.matcher(content);
	    if( m.matches() )
	    	return 2;	//汉字
	    return -1;	//什么鬼都不是
	}
	
	public void writeLocalFile(String key, String value)
	{
		final SharedPreferences sp = mActivity.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
		sp.edit().remove(key).commit();
		Editor editor = sp.edit();
	    editor.putString(key, value);
	    editor.commit();
	}
	
	public String readLocalFile(String key)
	{
		final SharedPreferences sp = mActivity.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
		String res = sp.getString(key, "");
		return res;
	}
	
	public void removeLocalFile(String key)
	{
		final SharedPreferences sp = mActivity.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
		sp.edit().remove(key).commit();
	}
	
	public void deleteFile(String fileName)
	{
		deleteFile(new File(fileName));
	}
	
	public static void deleteFile(File file) 
	{
		if (file.isFile()) {
			file.delete();
			return;
		}
		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				deleteFile(childFiles[i]);
			}
			file.delete();
		}
	}
	
	public static void delayAction(final int time, final OnMyCallBack o)
	{
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(time);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(o != null)
					o.onReceive("", -1, null);
			}
		}).start();
	}
	
	public int getWidth() {
		if (mWidth < 0)
			getScreenParameters();
		return mWidth;
	}

	public int getHeight() {
		if (mHeight < 0)
			getScreenParameters();
		return mHeight;
	}

	private void getScreenParameters() {
		DisplayMetrics dm = new DisplayMetrics();
		dm = mActivity.getResources().getDisplayMetrics();

		mWidth = dm.widthPixels;
		mHeight = dm.heightPixels;
	}
	//坐标转换
	public int _tw(int origina_lw)
	{
		final float W = 1280;
		float realW = getWidth();
		float ret = (realW * (float)origina_lw) / W;
		return (int)ret;
	}
	public int _th(int origina_lh)
	{
		final float H = 720;
		float realH = getHeight();
		float ret = (realH * (float)origina_lh) / H;
		return (int)ret;
	}
	
	// ---------------------------------------------------------------------

	public void setScreenOrientationLandscape(Activity tpActivity) {
		setCurActivity(tpActivity);
		tpActivity.requestWindowFeature(Window.FEATURE_NO_TITLE);
		tpActivity.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		tpActivity.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	public void releaseGameRes() {
		finishAllActivity();
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}

	private void finishAllActivity() {
		for (int i = 0; i < mActivityLists.size(); i++) {
			if ((mActivityLists.get(i) != null)
					&& (!mActivityLists.get(i).isFinishing()))
				mActivityLists.get(i).finish();
		}
	}

	private static boolean isEmpty(String arg0) {
		if (arg0 == null || arg0.equals(""))
			return true;

		return false;
	}
	
	private static int num = 0;
	private static String dd = ".";
	public String getSomeThing(boolean _isReset)
	{
		if(_isReset)
			num = 0;
		if(num >= 4)
			num = 0;
		String ret = "";
		for(int i = 0; i < num; i++)
			ret += dd;
		for(int i = num; i < 3; i++)
			ret += " ";
		num++;
		return ret;
	}
	
}
